package com.qc.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.qc.common.Constants;
import com.qc.common.DBHandler;
import com.qc.common.DBUtil;
import com.qc.common.DateUtil;
import com.qc.common.SMSClient;
import com.qc.common.Util;
import com.qc.entity.BusinessReceive;
import com.qc.entity.ConfigEntity;
import com.qc.entity.Coupon;
import com.qc.entity.OrderEntity;
import com.qc.entity.OrderScheduleEntity;
import com.qc.entity.UserEntity;
import com.qc.entity.UserMoneyLogEntity;
import com.qc.jpush.JPushUtil;
import com.qc.service.BusinessReceiveService;
import com.qc.service.ConfigService;
import com.qc.service.CouponService;
import com.qc.service.OrderService;
import com.qc.service.UserService;

@Component
public class FlightTrainTask {

    @Autowired
    private DataSource dataSource;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CouponService couponService;
    
    @Autowired
    private BusinessReceiveService businessReceiveService;
    
    @Resource(name="configService")
    private ConfigService configService;
    
    @Scheduled(cron = "0 */10 * * * ? ") // 间隔5秒执行
    public void sendMessage() {
        
        long l = System.currentTimeMillis();
        Date date = new Date(l);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //转换提日期输出格式
        
        System.out.println("sendMessage 定时任务" + dateFormat.format(date));
        
        long curren = System.currentTimeMillis();
        curren += 60 * 60 * 1000;
        Date da = new Date(curren);
        
        List<OrderScheduleEntity> list = orderService.getAllOrderByDate(dateFormat.format(date),dateFormat.format(da));
        
        if (list.size()>0) {
            for (OrderScheduleEntity entity : list) {
                JPushUtil.orderMessage(entity, entity.getBossUserId());
                
                //修改push状态
                orderService.updateOrderSchedulePush(entity.getOrderScheduleId());
                
                Util.logExceptionINFO("sendMessage jieshu ----" +dateFormat.format(date) );
                
                
                System.out.println("timerSmsRemind 三分钟 结束+++ " +dateFormat.format(date));
            }
        }
    }
    
    
    /**
     * 每天晚6点跑第二天开始的订单
     */
    @Scheduled(cron = "0 0 18 * * ? ") // 间隔5秒执行
    public void timerSmsRemind() {
      //run中填写定时器主要执行的代码块
        long l = System.currentTimeMillis();
        //new日期对象
        Date date = new Date(l);
        //转换提日期输出格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        System.out.println("timerSmsRemind 定时任务" + dateFormat.format(date));
        
        Util.logExceptionINFO("timerSmsRemind kaishi ---------" +dateFormat.format(date));
        
        List<OrderEntity> list = getAllOrderByDate();
        if (list.size()>0) {
            for (OrderEntity orderEntity : list) {
                
                SMSClient.beginOrder(orderEntity);
                
                Util.logExceptionINFO("timerSmsRemind jieshu ----" +dateFormat.format(date) );
            }
        }
    }
    
    public static void main(String[] args) {
    	 long l = System.currentTimeMillis();
         //new日期对象
         Date date = new Date(l);
         //转换提日期输出格式
         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
         String time = dateFormat.format(date) + ":00";
         System.out.println("orderSettlement 定时任务" + time);
	}
    
    /**
     * 订单结算
     * 订单开始
     * @param args
     */
    @Scheduled(cron = "0 0 */1 * * ? ")
    public void orderSettlement(){
    	
    	System.out.println("每小时执行一次");
    	
        long l = System.currentTimeMillis();
        //new日期对象
        Date date = new Date(l);
        //转换提日期输出格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
        
        String time = dateFormat.format(date) + ":00";
        
        System.out.println("orderSettlement 定时任务" + time);
        
        //开始时间查询
        List<OrderEntity> listStart = orderService.getAllOrderTime(time, "");
        if (listStart.size()>0) {
        	
        	for (OrderEntity orderEntity : listStart) {
                String orderId = String.valueOf(orderEntity.getOrderId());
                //修改状态
                orderService.updateOrderState(orderId, "3");
            }
        }
        
        int flag = 0;
        
        List<OrderEntity> listEnd = orderService.getAllOrderTime("", time);
        if (listEnd.size()>0) {

        	for (OrderEntity orderEntity2 : listEnd) {
                String orderId = String.valueOf(orderEntity2.getOrderId());
                //修改订单状态
                orderService.updateOrderState(orderId, "4");
                
                //查询分账比例
                double scale = 0;
                List<ConfigEntity> list = configService.getOrderScale();
                if (list != null && list.size() > 0) {
                    ConfigEntity configEntity2 = list.get(0);
                    scale = configEntity2.getScale();
                }
                
                //用户交易数加一
                flag = userService.updateTransactionNumber(orderEntity2.getBossUserId());
                if (flag == 0) {
                	  Util.logExceptionINFO("orderEntity2.getBossUserId() cuowu :" +orderEntity2.getBossUserId());
                }
                
                //用户交易数加一
                flag = userService.updateTransactionNumber(orderEntity2.getSecretaryUserId());
                if (flag == 0) {
              	  Util.logExceptionINFO("orderEntity2.getSecretaryUserId() cuowu :" +orderEntity2.getSecretaryUserId());
                }
                
                UserEntity uEntity = userService.getUserInfoByUserId(orderEntity2.getSecretaryUserId());
                //TODO: 这里应该判断是否加了优惠券，还有快递费，第一版就暂时全部分成
                double clearMoney = orderEntity2.getMoney();
                //结算订单金额
                if (scale > 0) {
                    clearMoney = clearMoney * scale;
                }
                
                //秘书余额增加金额
                long state = userService.updateUserBalance(uEntity.getBalance() + clearMoney, orderEntity2.getSecretaryUserId());
                if (state > 0) {
                    //加log
                    UserMoneyLogEntity entity = new UserMoneyLogEntity();
                    entity.setUserId(orderEntity2.getSecretaryUserId());
                    entity.setHappenMoney(clearMoney);
                    entity.setDescription("订单结算");
                    userService.addMoneyLog(entity);
                }
            }
        }
    }
    
    public List<OrderEntity> getAllOrderByDate() {

        List<Object> l = new ArrayList<Object>();
        l.add(DateUtil.currentLaterOne());
        
        List<OrderEntity> list = new ArrayList<OrderEntity>();
        DBHandler dbHandler = new DBHandler();
        try {

            dbHandler.rs = dbHandler.query(DBUtil.getSql(Constants.SELECT_ALL_ORDER_BYDATE), l, dataSource);
            while(dbHandler.rs.next()){

                OrderEntity entity = OrderEntity.getInstance(dbHandler.rs);
                
                list.add(entity);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            dbHandler.closeAll();
        }
        return null;
    }
    
    /**
     * 优惠券定时器  每天判断优惠券是否过期
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    //@Scheduled(cron = "0 */1 * * * ? ")
    public void couponCouponType(){
    	
    	String endTime = DateUtil.getAfterOneDay2();
        
        System.out.println("orderSettlement 定时任务" + endTime);
    	
    	//查询所有商家 的优惠券
    	List<Coupon> listCoupon = couponService.listAllCouponType();
    	for (Coupon coupon : listCoupon) {
    		
    		//优惠券日期 和 系统当前时间 是否相等 如果想等 修改为 1过期
    		if (coupon.getCouponEndDate().equals(endTime) ) {
    			
    			coupon.setCouponType(1);
    			coupon.setShelvesState(3);
    			coupon.setbId(coupon.getbId());
    			
    			couponService.updateCouponId(coupon);
    			
    			//用户领取此 优惠券也改为过期
    			List<BusinessReceive> listBusinessReceive = businessReceiveService.listeceive(0, 0, coupon.getbId());
    			if (listBusinessReceive.size()>0) {
    				
    				for (BusinessReceive businessReceive : listBusinessReceive) {
    					
    					businessReceive.setState(2);
    					businessReceive.setbId(businessReceive.getId());
    					
    					businessReceiveService.updateBusinessReceiveState(businessReceive);
    					
    				}
    			}
    		}
    	}
    }
    
    /**
     * 优惠券活动过期
     */
    @Scheduled(cron = "0 0 2 * * ? ")
   // @Scheduled(cron = "0 */2 * * * ? ")
    public void couponOverdueState(){
        
        String endTime = DateUtil.getAfterOneDay2();
        
        System.out.println("couponOverdueState 定时任务" + endTime);
    	
    	//查询所有商家 的优惠券
    	List<Coupon> listCoupon = couponService.listAllCouponOverdueState();
    	for (Coupon coupon : listCoupon) {
    		
    		//优惠券 活动结束时间
    		if (coupon.getEndDate().equals(endTime) ) {
    			
    			coupon.setOverdueState(1);
    			coupon.setbId(coupon.getbId());
    			
    			couponService.updateCouponId(coupon);
    		}
    	}
    }
    
    
}
